package de.dhbw.asa.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import de.dhbw.asa.model.Adress;
import de.dhbw.asa.model.Customer;

@ManagedBean
@SessionScoped
public class RegisterCtrl {
	
	@ManagedProperty(value = "#{customer}")
	Customer customer;
	
	String sPassword1;
	String sPassword2;
	
	/*
	 * this methode returns eighter 'failure' or 'success' wheather the registration of the new customer was
	 * successful or not
	 * if the two passwords don't match, we return 'password' for special error handling
	 */
	public String register(Adress jNew)
	{
		String sReturn = "failure";
		// we should test wheather the two entered passwords are equal
		if (this.sPassword1.equals(this.sPassword2))
		{
			if (customer.saveNewCustomer(customer.getsForename(), customer.getsLastname(), customer.getsTitle(), this.sPassword1).equals(""))
			{
				if (jNew.saveNewAdress(customer, jNew.getsStreet(), jNew.getsHouseNr(), jNew.getiPostcode(), jNew.getsCountry(), jNew.getsCity()).equals(""))
				{
					// the customer was written into the database successfully
					// also the adress
					sReturn = "success";
					//load the adresses of the customer
					customer.jAdressList=customer.loadAllAdresses();
				}
				else
				{
					// customer was written successfully but there was an error while writing the adress
					sReturn ="adressFailure";
				}
			}
			else
			{
				// error while writing the customer into the database
				sReturn = "customerFailure";
			}
		}
		else
		{
			// the two entered passwords don't match. Special error handling!!
			sReturn = "password";
		}
		return sReturn;
	}
	
	/*
	 * we take the entries of the 'change customer information'-form and save these changes
	 */
	public String changeCustomer()
	{
		String sReturn = "failure";
		// we should test wheather the two entered passwords are equal
		if (this.sPassword1.equals(this.sPassword2))
		{
			if (customer.saveChanges().equals(""))
			{
				// the customer was written into the database successfully
				sReturn = "success";
			}
			else
			{
				// error while writing into the database
				sReturn = "failure";
			}
		}
		else
		{
			// the two entered passwords don't match. Special error handling!!
			sReturn = "password";
		}
		return sReturn;
	}

	public Customer getCustomer() 
	{
		return customer;
	}

	public void setCustomer(Customer customer) 
	{
		this.customer = customer;
	}

	public String getsPassword1() 
	{
		return sPassword1;
	}

	public void setsPassword1(String sPassword1) 
	{
		this.sPassword1 = sPassword1;
	}

	public String getsPassword2() 
	{
		return sPassword2;
	}

	public void setsPassword2(String sPassword2) 
	{
		this.sPassword2 = sPassword2;
	}

}
